package com.rf.richfitwheel.common.utils;

import org.springframework.lang.Nullable;

import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.regex.Pattern;

public class StringUtils {

	public static final String LINE_SEPARATOR = "\r\n";

	public static final String LINE_SEPARATOR_JSP = "<br>";

	public static final String EMPTY = "";

	/**
	 * 判断String是否为空
	 * 
	 * @param str
	 * @return 空为true
	 */
	public static Boolean isNullString(String str) {
		if (str == null || "".equals(str)) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	/**
	 * 判null, 判空，同时判trim后是否为空
	 * @param str
	 * @return
	 */
	public static boolean isVoid(@Nullable String str) {
		return str == null ? Boolean.TRUE :
				("".equals(str.trim()) ? Boolean.TRUE : Boolean.FALSE);
	}

	public static String getThrowableInfo(Throwable t) {
		StringBuffer sb = new StringBuffer();

		if (t == null) {
			return "";
		}
		Throwable t2 = t;
		if (t instanceof RemoteException) {
			t2 = getDetailOfRemoteEx((RemoteException) t);
		}
		sb.append(t.getLocalizedMessage());
		sb.append(StringUtils.LINE_SEPARATOR);
		sb.append('[');
		sb.append(t2.getClass().getName());
		sb.append(' ');
		if (t2 instanceof SQLException) {
			sb.append(((SQLException) t2).getErrorCode());
			sb.append(' ');
			sb.append(((SQLException) t2).getMessage());
			sb.append(' ');
		}
		sb.append(StringUtils.LINE_SEPARATOR);

		StackTraceElement[] stes = null;
		Throwable ttmp = t;
		int count = 0;
		String throwname = null;
		String msg = null;
		StringBuffer causesb = new StringBuffer();
		causesb.append(StringUtils.LINE_SEPARATOR);
		while (null != ttmp) {
			stes = ttmp.getStackTrace();
			throwname = ttmp.getClass().getName();
			msg = ttmp.getLocalizedMessage();
			if (null == msg) {
				msg = ttmp.getMessage();
			}

			if (0 != count && null != msg && !"".equals(msg)) {
				causesb.append("Caused By: " + throwname + ": " + msg);
				causesb.append(StringUtils.LINE_SEPARATOR);
			} else if (1 <= count) {
				causesb.append("Caused By: " + throwname);
				causesb.append(StringUtils.LINE_SEPARATOR);
			}

			for (int i = 0; i < stes.length; i++) {
				count++;
				sb.append(" at ");
				sb.append(stes[i].toString());
				sb.append(StringUtils.LINE_SEPARATOR);
			}

			ttmp = ttmp.getCause();
		}

		sb.append(']');

		return causesb.append(sb).toString();
	}

	private static Throwable getDetailOfRemoteEx(RemoteException re) {
		Throwable ret = null;
		ret = re.detail;
		while (ret instanceof RemoteException) {
			ret = ((RemoteException) ret).detail;
		}
		return ret;
	}

	/**
	 * 一次性判断多个或单个对象为空。
	 * 
	 * @param objects
	 * @author cai niao
	 * @return 只要有一个元素为Blank，则返回true
	 */
	public static boolean isBlank(Object... objects) {
		Boolean result = false;
		for (Object object : objects) {
			if (object == null || "".equals(object.toString().trim()) || "null".equals(object.toString().trim())
					|| "[null]".equals(object.toString().trim()) || "[]".equals(object.toString().trim())) {
				result = true;
				break;
			}
		}
		return result;
	}

	/**
	 * 一次性判断多个或单个对象不为空。
	 * 
	 * @param objects
	 * @author zhou-baicheng
	 * @return 只要有一个元素不为Blank，则返回true
	 */
	public static boolean isNotBlank(Object... objects) {
		return !isBlank(objects);
	}

	public static String checkNullToConvert(Object obj) {
		return StringUtils.isBlank(obj) ? "" : obj.toString();
	}

	/**
	 * 判断一个字符串在数组中存在几个
	 * 
	 * @param baseStr
	 * @param strings
	 * @return
	 */
	public static int indexOf(String baseStr, String[] strings) {

		if (null == baseStr || baseStr.length() == 0 || null == strings)
			return 0;

		int i = 0;
		for (String string : strings) {
			boolean result = baseStr.equals(string);
			i = result ? ++i : i;
		}
		return i;
	}

	/**
	 * 判断一个字符串是否为JSONObject,是返回JSONObject,不是返回null
	 * 
	 * @param args
	 * @return
	 */
	public static net.sf.json.JSONObject isJSONObject(Object args) {
		net.sf.json.JSONObject result = null;

		if (args instanceof net.sf.json.JSONObject) {
			return (net.sf.json.JSONObject) args;
		}

		if (isBlank(args)) {
			return result;
		}
		try {
			return net.sf.json.JSONObject.fromObject(args);
		} catch (Exception e) {
			return result;
		}
	}

	/**
	 * 判断一个字符串是否为JSONArray,是返回JSONArray,不是返回null
	 * 
	 * @param args
	 * @return
	 */
	public static net.sf.json.JSONArray isJSONArray(Object args) {

		if (args instanceof net.sf.json.JSONArray) {
			return (net.sf.json.JSONArray) args;
		}

		net.sf.json.JSONArray result = null;
		if (isBlank(args)) {
			return result;
		}
		try {
			return net.sf.json.JSONArray.fromObject(args);
		} catch (Exception e) {
			return result;
		}
	}

	public static String trimToEmpty(Object str) {
		return (isBlank(str) ? "" : str.toString().trim());
	}

	/**
	 * 转换成Unicode
	 * 
	 * @param str
	 * @return
	 */
	public static String toUnicode(String str) {
		String as[] = new String[str.length()];
		String s1 = "";
		for (int i = 0; i < str.length(); i++) {
			as[i] = Integer.toHexString(str.charAt(i) & 0xffff);
			s1 = s1 + "\\u" + as[i];
		}
		return s1;
	}

	/**
	 * 替换字符串
	 * 
	 * @param str
	 * @param nowStr
	 * @param replaceStr
	 * @return
	 */
	public static String replaceString(String str, String nowStr, String replaceStr) {

		nowStr = StringUtils.isBlank(nowStr) ? "" : nowStr;
		replaceStr = StringUtils.isBlank(replaceStr) ? "" : replaceStr;

		if (StringUtils.isNotBlank(str)) {

			return str.replaceAll(nowStr, replaceStr);
		}
		return "";
	}

	public static  boolean  isEqule(Object a,Object b) {
		if (StringUtils.isBlank(a)) {
			return false;
		}
		if (StringUtils.isBlank(b)) {
			return false;
		}
		if(a.toString()==b.toString()||a.toString().equals(b.toString())) {
			return true;
		}
		return false;
	}
	
	public static String trim(String str) {
		return str == null ? null : str.trim();
	}

	public static String trimToNull(String str) {
		String st = trim(str);
		return isNullString(st) ? null : st;
	}

	public static String trimToEmpty(String str) {
		return str == null ? EMPTY : str.trim();
	}
	
	/**
	 * 
	 * <p>Title: sql注入字符过滤</p>  
	 * <p>Description: 优先使用占位符方式实现sql而不是使用此方法</p>  
	 * @param str 过滤后的字符串
	 * @return
	 */
	public static String doSQLFilter(String str){
	     str=str.replaceAll(";","");
	    str=str.replaceAll("&","&amp;");
	     str=str.replaceAll("<","&lt;");
	     str=str.replaceAll(">","&gt;");
	     str=str.replaceAll("'","");
	     str=str.replaceAll("--","");
	     str=str.replaceAll("/","");
	     str=str.replaceAll("%","");
	   return str;
	}
	
	/**
	 * 依据分割符分割字段并拼装sql查询条件
	 * @param column 表的字段
	 * @param delimiter 分隔符
	 * @param searchStr 需分割字段
	 * @return 返回拼装sql
	 */
	public static String analysisLikeString(String column,String delimiter,String searchStr) {
		if(isNotBlank(searchStr)) {
			String[] split = searchStr.split(delimiter);
			StringBuilder sql = new StringBuilder(" and (");
			for(int i=0;i<split.length;i++) {
				if(i==0) {
					sql.append(" "+column+" like '%"+split[0]+"%'");
				}else {
					sql.append(" or "+column+" like '%"+split[i]+"%'");
				}
			}
		    sql.append(" )");
			return sql.toString();
		}
		return null;
	}
	/**
	 * 依据分割符分割字段并拼装sql查询条件
	 * @param column 表的字段
	 * @param delimiter 分隔符
	 * @param searchStr 需分割字段
	 * @return 返回拼装sql
	 */
	public static String analysisInString(String column,String delimiter,String searchStr) {
		if(isNotBlank(searchStr)) {
			String[] split = searchStr.split(delimiter);
			StringBuilder sql = new StringBuilder(" and "+column+" in(");
				for (int i = 0; i < split.length; i++) {
					if (i <= 0) {
						sql.append("'" + split[i] + "'");
					} else {
						sql.append(",'" + split[i] + "'");
					}
				}
				sql.append(" )");
			return sql.toString();
		}
		return null;
	}

	/**
	 * 校验字符串   只能由字母或者数字组成
	 * @param str
	 * @return
	 */
	public static boolean isValidAlphaNumeric(String str) {
		// 使用正则表达式检查字符串是否只包含字母和数字
		// ^ 表示匹配字符串的开头
		// [a-zA-Z0-9] 表示匹配任意字母（大小写不区分）或数字
		// + 表示匹配一个或多个前面的字符
		// $ 表示匹配字符串的结尾
		String regex = "^[a-zA-Z0-9]+$";
		return Pattern.matches(regex, str);
}
}
